package com.czk.getApplcationContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 第三种方式
 * 实现ApplicationListener接口
 * 调用顺序 applicationAware->beanFactoryAware->applicationListener<ContextRefreshedEvent></> 三种方式
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/28 15:10
 */
@Component
public class ApplicationListenerUtils implements ApplicationListener<ContextRefreshedEvent> {
    private static ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("onApplicationEvent被调用了");
        // 拿到上下文
        applicationContext = contextRefreshedEvent.getApplicationContext();
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}
